/*
 *    Copyright 2009-2022 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.JdbcType;

/**
 * XMLConfigBuilder BaseBuilder 的众多子类之一，它扮演的是具体建造者的角色。
 * XMLConfigBuilder 主要负责解析 mybatis-config.xml 配置文件
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
public class XMLConfigBuilder extends BaseBuilder {
  /**
   * 标识是否已经解析 mybatis-config.xml 配置丈件
   */
  private boolean parsed;

  /**
   * 用于解析 mybatis-config xml 配置文件的 XPathParser 对象
   */
  private final XPathParser parser;

  /**
   * 标识＜environment＞配置的名称，默认读取＜environment＞标签的 default 属性
   */
  private String environment;

  /**
   * ReflectorFactory 负责创建和缓存 Reflector 对象
   */
  private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

  public XMLConfigBuilder(Reader reader) {
    this(reader, null, null);
  }

  public XMLConfigBuilder(Reader reader, String environment) {
    this(reader, environment, null);
  }

  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
    this(Configuration.class, reader, environment, props);
  }

  public XMLConfigBuilder(Class<? extends Configuration> configClass, Reader reader, String environment, Properties props) {
    this(configClass, new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  public XMLConfigBuilder(InputStream inputStream) {
    this(inputStream, null, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment) {
    this(inputStream, environment, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
    this(Configuration.class, inputStream, environment, props);
  }

  public XMLConfigBuilder(Class<? extends Configuration> configClass, InputStream inputStream, String environment, Properties props) {
    this(configClass, new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  private XMLConfigBuilder(Class<? extends Configuration> configClass, XPathParser parser, String environment, Properties props) {
    super(newConfig(configClass));
    ErrorContext.instance().resource("SQL Mapper Configuration");
    this.configuration.setVariables(props);
    this.parsed = false;
    this.environment = environment;
    this.parser = parser;
  }

  /**
   * 是解析 mybatis-config.xml 配置文件的入口，它通过调用
   * XMLConfigBuilder.parseConfiguration() 方法实现整个解析过程
   */
  public Configuration parse() {
    // 1. ．．．根据 parsed 变量的位，判断是否 已经完成了对 mybatis-config.xml 配置文件的解析
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;

    // 2. 在 mybatis-config.xml 配置文件中查找＜configuration＞节点，并开始解析
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

  /**
   * 封装了整体的解析逻辑
   */
  private void parseConfiguration(XNode root) {
    try {
      // issue #117 read properties first
      // 1. 解析＜properties＞节点
      propertiesElement(root.evalNode("properties"));
      // 2. 解析＜settings＞节点
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      // 3. 设置 vfsImpl 字段
      loadCustomVfs(settings);
      // 4. 设置自定义的日志实现类
      loadCustomLogImpl(settings);
      // 5. 解析＜typeAliases＞节点
      typeAliasesElement(root.evalNode("typeAliases"));
      // 6. 解析＜plugins＞节点
      pluginElement(root.evalNode("plugins"));
      // 7. 解析＜objectFactory＞节点
      objectFactoryElement(root.evalNode("objectFactory"));
      // 8. 解析＜objectWrapperFactory＞节点
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      // 9. 解析＜reflectorFactory＞节点
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      // 10. 将 settings 值设置到 Configuration 中
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      // 11. 解析＜environments＞节点
      environmentsElement(root.evalNode("environments"));
      // 12. 解析＜databaseIdProvider＞节点
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      // 13. 解析＜typeHandlers＞节点
      typeHandlerElement(root.evalNode("typeHandlers"));
      // 14. 解析＜mappers＞节点
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

  /**
   * 解析方式与 propertiesElement（） 方法类似 但是多了使用
   * MetaClass 检测 key 定的属性在 Configuration 类中是否有对应 setter 方法的步骤。
   */
  private Properties settingsAsProperties(XNode context) {
    if (context == null) {
      return new Properties();
    }

    // 1. 解析＜ settings ＞的子节点（＜ setting ＞标签）的 name 和 value 属性，并返回 Properties 对象
    Properties props = context.getChildrenAsProperties();
    // Check that all settings are known to the configuration class
    // 2. 创建 Configuration 对应的 MetaClass 对象
    MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
    // 3. 检测 Configuration 是否定义了 key 指定属性相应的 setter 方法
    for (Object key : props.keySet()) {
      if (!metaConfig.hasSetter(String.valueOf(key))) {
        throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
      }
    }
    return props;
  }

  private void loadCustomVfs(Properties props) throws ClassNotFoundException {
    String value = props.getProperty("vfsImpl");
    if (value != null) {
      String[] clazzes = value.split(",");
      for (String clazz : clazzes) {
        if (!clazz.isEmpty()) {
          @SuppressWarnings("unchecked")
          Class<? extends VFS> vfsImpl = (Class<? extends VFS>)Resources.classForName(clazz);
          configuration.setVfsImpl(vfsImpl);
        }
      }
    }
  }

  private void loadCustomLogImpl(Properties props) {
    Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
    configuration.setLogImpl(logImpl);
  }

  /**
   * 解析＜ typeAliases＞节点及其子节点，并通
   * TypeAliasRegis 完成别名的注册
   */
  private void typeAliasesElement(XNode parent) {
    if (parent != null) {
      // 1. 处理全部子节点
      for (XNode child : parent.getChildren()) {
        // 2. 处理＜package ＞节点
        if ("package".equals(child.getName())) {
          // 3. 获取指定的包名
          String typeAliasPackage = child.getStringAttribute("name");
          // 4. 通过 TypeAliasRegistry 扫描指定包中所有的类，并解析＠Alias 注解，完成别名注册
          configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
        } else {
          // 5. 处理＜ typeAlias ＞节点
          // 6. 获取指定的别名
          String alias = child.getStringAttribute("alias");
          // 7. 获取别名对应的类型
          String type = child.getStringAttribute("type");
          try {
            Class<?> clazz = Resources.classForName(type);
            if (alias == null) {
              // 8. 扫描＠ Alias主解，完成注册
              typeAliasRegistry.registerAlias(clazz);
            } else {
              // 9. 注册别名
              typeAliasRegistry.registerAlias(alias, clazz);
            }
          } catch (ClassNotFoundException e) {
            throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
          }
        }
      }
    }
  }

  /**
   * 插件是 MyBatis 提供的扩展机制之一 ，用户可以通过添加自定义插件在 SQL 语句执行过程
   * 中的某一点进行拦截。 MyBatis 中的自定义插件只需实现 Interceptor 接口，并通过注解指定想
   * 要拦截的方法签名即可。这里先来分析 MyBatis 中如何加载和管理插件
   */
  private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      // 1. 追历全部子节点（即 <plugin ＞节点）
      for (XNode child : parent.getChildren()) {
        // 2. 获取＜plugin ＞节点的 interceptor 属性的值
        String interceptor = child.getStringAttribute("interceptor");
        // 3. 获取＜plugin ＞节点下＜properties ＞配置的信息，并形成 Properties 对象
        Properties properties = child.getChildrenAsProperties();
        // 4. 通过前面介绍 TypeAliasRegistry 解析别名之后，实例化 Interceptor 对象
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
        // 5. 设置 Interceptor 的属性
        interceptorInstance.setProperties(properties);
        // 6. 记录 Interceptor 对象
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }

  /**
   * 1、基础支持层提到过，我们可以通过添加自定义 ObjectFactory 实现类、ObjectWrapperFactory 实现 ReflectorFactory 实现类对 MyBatis 进行扩展。
   * 2、负责解析井实例化＜objectFactory＞节点指定 ObjectFactory 实现类，之后将自定义的 ObjectFactory 对象记录到 Configuration.objectFactory字段中
   */
  private void objectFactoryElement(XNode context) throws Exception {
    if (context != null) {
      // 1. 获取＜objectFactory 节点的 type 属性
      String type = context.getStringAttribute("type");
      // 2. 获取＜ objectFactory ＞节点下配的信息，并形成 Properties 对象
      Properties properties = context.getChildrenAsProperties();
      // 3. 进行别名解析后，实例化自定义 ObjectFactory 实现
      ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      // 4. 设置自定义 ObjectFactory 的属性，完成初始化的相关操作
      factory.setProperties(properties);
      // 5. 将自定义 ObjectFactory 对象记录 configuration 对象的 objectFactory 字段中，待后续使用
      configuration.setObjectFactory(factory);
    }
  }

  /**
   * 类似 objectFactoryElement
   */
  private void objectWrapperFactoryElement(XNode context) throws Exception {
    // ...
    if (context != null) {
      String type = context.getStringAttribute("type");
      ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      configuration.setObjectWrapperFactory(factory);
    }
  }

  /**
   * 类似 objectFactoryElement
   */
  private void reflectorFactoryElement(XNode context) throws Exception {
    // ...
    if (context != null) {
      String type = context.getStringAttribute("type");
      ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      configuration.setReflectorFactory(factory);
    }
  }

  /**
   * 解析 mybatis-config.xml 配置 文件中的<properties＞节点并形 java.util.Properties 对象，
   * 之后将该 Properties 对象设置到 XPathParser 和 Configuration 的 variable 字段中。
   * 在后面的解析过程中，会使用该 Properties 对象中的信息替换占位符。
   * @param context
   * @throws Exception
   */
  private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      // 1. 解析＜properties ＞的子节点（＜property 标签）的 name 和 value 属性，并记录到 Properties
      Properties defaults = context.getChildrenAsProperties();
      // 2. 解析＜properties ＞的 resource 和 url 属性,I 这两个属性用于确定 properties 配置文件的位置
      String resource = context.getStringAttribute("resource");
      String url = context.getStringAttribute("url");
      // 3. ... resource 属性和 url 属性不能同时存在，否则会抛出异常（略）
      // 加载 resource 属性或 url 属性指定的 properties 文件，使用到 Resources 工具类
      if (resource != null && url != null) {
        throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
      }
      // 4. ．．．与 Configuration 对象中 variables 集合合并
      if (resource != null) {
        defaults.putAll(Resources.getResourceAsProperties(resource));
      } else if (url != null) {
        defaults.putAll(Resources.getUrlAsProperties(url));
      }
      Properties vars = configuration.getVariables();
      if (vars != null) {
        defaults.putAll(vars);
      }
      // 5. 更新 XPathParser 和 Configuration variable 字段
      parser.setVariables(defaults);
      configuration.setVariables(defaults);
    }
  }

  /**
   * 解析＜settings＞节点，在＜settings＞节点下的
   * 配置是 MyBatis 全局性的配置，它们会改变 MyBatis 的运行时行为， 具体配置项含义请读者
   * 参考 MyBatis 官方文档。需要注意的是，在 MyBatis 初始化时，这些全局配置信息都会被记录
   * 到 Configuration 对象的对应属性中。例如，开发人员可以通过配置 autoMappingBehavior 修改
   * My Batis 是否开启自动映射的功能。
   *
   * @param props
   */
  private void settingsElement(Properties props) {
    configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
    configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
    configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
    configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
    configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
    configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
    configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
    configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
    configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
    configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
    configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
    configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
    configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));
    configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
    configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
    configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
    configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
    configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
    configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
    configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
    configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
    configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
    configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
    configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
    configuration.setLogPrefix(props.getProperty("logPrefix"));
    configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
    configuration.setShrinkWhitespacesInSql(booleanValueOf(props.getProperty("shrinkWhitespacesInSql"), false));
    configuration.setArgNameBasedConstructorAutoMapping(booleanValueOf(props.getProperty("argNameBasedConstructorAutoMapping"), false));
    configuration.setDefaultSqlProviderType(resolveClass(props.getProperty("defaultSqlProviderType")));
    configuration.setNullableOnForEach(booleanValueOf(props.getProperty("nullableOnForEach"), false));
  }

  /**
   * 1、在实际生产中 ，同一项目可能分为开发、 测试和生产多个不同的环境，每个环境的配置可
   * 能也不尽相同 MyBatis 可以配置多个 environment>节点，每个＜environment>节点对应一种环
   * 境的配置。但需要注意的是，尽管可以配置多个环境，每个 SqlSessionFactory 实例只能选择其一；
   * 2、XMLConfigBuilder.environmentsElement()方法负责解析 environments＞的相关配置，它会根据
   * XMLConfigBuilder.environment 宇段值确定要使用的 environment>配置，之后创建对应的
   * TransactionFactory 和 DataSource 对象，井封装进 Environment 对象中。
   */
  private void environmentsElement(XNode context) throws Exception {
    if (context != null) {
      if (environment == null) {
        // 1. 未指定 XMLConfigBuilder.environment 字段，则使用 default 属性指定的 <environment>
        environment = context.getStringAttribute("default");
      }
      // 2. 遍历子节点（即＜environment 节点）
      for (XNode child : context.getChildren()) {
        String id = child.getStringAttribute("id");
        if (isSpecifiedEnvironment(id)) {
          // 3. 与 XMLConfigBuilder.environment 字段匹配创建 TransactionFactory ，具体实现是先通过 TypeAliasRegistry 解析别名之后，
          // 实例化 TransactionFactory
          TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
          // 4. 创建 DataSourceFactory 和 DataSource
          DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
          DataSource dataSource = dsFactory.getDataSource();
          // 5. 创建 Env ronment, Environment 中封装了上面创建的 TransactionFactory 对象以及 DataSource 对象 这里应用了建造者模式
          Environment.Builder environmentBuilder = new Environment.Builder(id)
              .transactionFactory(txFactory)
              .dataSource(dataSource);
          // 6. 将 Environment 对象记录到 Configuration.environment 字段中
          configuration.setEnvironment(environmentBuilder.build());
          break;
        }
      }
    }
  }

  /**
   * 1、My Batis 不能像 Hibernate 那样， 直接帮助开 员屏蔽多种数据库产品在 SQL 语言支持方
   * 面的差异。但是在 mybatis-config nl 置文件中，通过＜databaseIdProvider＞定义所有支持的数
   * 据库产品的 databaseld ，然后在映射配置文件中定义 SQL 语句节点时，通过 databaseId 指定该
   * SQL 语句应用的数据库产品 ，这样也可以实现类似的功能。
   * 2、在 MyBatis 初始化时，会根据前面确定的 DataSource 确定当前使用的数据库产品，然后在
   * 解析映射配置文件时，加载不带 databaseId 属性和带有匹配当前数据库 databaseId 属性的所有
   * SQL 语句。如果同时找到带有 databaseId 和不带 databaseId 相同语句，则后者会被舍弃，使
   * 用前者。
   * 3、XMLConfigBuilder.databaseIdProviderElement（） 方法负责解析＜databaseIdProvider＞节点，井
   * 创建指定的 DatabaseIdProvider 对象。 DatabaseIdProvider 会返回 databaseId 值， MyBatis 会根据
   * databaseId 选择合适的 SQL 进行执行
   */
  private void databaseIdProviderElement(XNode context) throws Exception {
    DatabaseIdProvider databaseIdProvider = null;
    if (context != null) {
      String type = context.getStringAttribute("type");
      // awful patch to keep backward compatibility
      // 1. 为 了保证兼容性，修改 type 取值
      if ("VENDOR".equals(type)) {
        type = "DB_VENDOR";
      }
      // 2. 解析相关配置信息
      Properties properties = context.getChildrenAsProperties();
      // 3. 创建 DatabaseIdProvider 对象
      databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();
      // 4. 配置 DatabaseIdProvider ，完成初始化
      databaseIdProvider.setProperties(properties);
    }
    Environment environment = configuration.getEnvironment();
    if (environment != null && databaseIdProvider != null) {
      // 5. 通过前面确定的 DataSource 获取 databaseId 并记录到 Configuration.databaseId 字段
      String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
      configuration.setDatabaseId(databaseId);
    }
  }

  private TransactionFactory transactionManagerElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a TransactionFactory.");
  }

  private DataSourceFactory dataSourceElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a DataSourceFactory.");
  }

  private void typeHandlerElement(XNode parent) {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String typeHandlerPackage = child.getStringAttribute("name");
          typeHandlerRegistry.register(typeHandlerPackage);
        } else {
          String javaTypeName = child.getStringAttribute("javaType");
          String jdbcTypeName = child.getStringAttribute("jdbcType");
          String handlerTypeName = child.getStringAttribute("handler");
          Class<?> javaTypeClass = resolveClass(javaTypeName);
          JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
          Class<?> typeHandlerClass = resolveClass(handlerTypeName);
          if (javaTypeClass != null) {
            if (jdbcType == null) {
              typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
            } else {
              typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
            }
          } else {
            typeHandlerRegistry.register(typeHandlerClass);
          }
        }
      }
    }
  }

  /**
   * 法负责解析＜mappers＞节点，它会创
   * XMLMapperBuilder 对象加载映射文件，如果映射配置文件存在相应的 Mapper 接口，也会加载
   * 相应的 Mapper 接口，解析其中的注解并完成向 MapperRegistry的注册。
   */
  private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      // 1. 处理＜mappers ＞的子节点
      for (XNode child : parent.getChildren()) {
        // 2. package ＞子节点
        if ("package".equals(child.getName())) {
          String mapperPackage = child.getStringAttribute("name");
          // 3. 扫描指定的包，并向 MapperRegistry 注册 Mapper 接口
          configuration.addMappers(mapperPackage);
        } else {
          // 4. 获取＜mapper ＞节点的 resource\ url\ class 属性，这三个属性互斥
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          // 5. 如果＜mapper ＞节点指定了 resource 或是 url 属性，则创建 XMLMapperBuilder 对象
          //并通过该对象解析 resource 或是 url 属性指定的 Mapper 配置文件
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
              // 6. 创建 XMLMapperBuilder 对象，解析映射配置
              XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
              mapperParser.parse();
            }
          } else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            try(InputStream inputStream = Resources.getUrlAsStream(url)){
              // 7. 创建 XMLMapperBuilder 对象 解析映射配置文件
              XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
              mapperParser.parse();
            }
          } else if (resource == null && url == null && mapperClass != null) {
            // 8. 如果＜mapper＞节点指定了 class 属性, 则向 MapperRegistry 注册该 Mapper
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }

  private boolean isSpecifiedEnvironment(String id) {
    if (environment == null) {
      throw new BuilderException("No environment specified.");
    }
    if (id == null) {
      throw new BuilderException("Environment requires an id attribute.");
    }
    return environment.equals(id);
  }

  private static Configuration newConfig(Class<? extends Configuration> configClass) {
    try {
      return configClass.getDeclaredConstructor().newInstance();
    } catch (Exception ex) {
      throw new BuilderException("Failed to create a new Configuration instance.", ex);
    }
  }

}
